import { message, Table, Input, Button, Popconfirm, Form, Select, Modal } from 'antd';
import { saveTieCardInformation, delTieCardInformation } from '@/services/business';
import styles from '../components.less';
import FormModal from './FormModal';
import { getValue, to } from '@/utils/smallTool';

const drawerWidth = '40%';
const editConfig = [
  {
    name: 'id',
    label: 'Id',
    type: 'input',
    hidden: true
  },
  {
    name: 'cityCode',
    label: '城市编码',
    type: 'input',
    hidden: true
  },
  {
    name: 'accPassType',
    label: '配置类型（修改or注册）',
    type: 'input',
    hidden: true
  },
  {
    name: 'type',
    label: '业务类型',
    type: 'input',
    hidden: true
  },
  {
    name: 'oldSerialNumber',
    key: 'serialNumber',
    label: '序号',
    type: 'input',
    hidden: true,
  },
  {
    name: 'serialNumber',
    label: '序号',
    type: 'input'
  },
  {
    name: 'paraValue',
    label: '参数值',
    type: 'input',
  },
  {
    name: 'paraName',
    label: '参数名称',
    type: 'input',
  },
  {
    name: 'paraPrompt',
    label: '参数提示',
    type: 'input',
  },
  {
    name: 'isDisplay',
    label: '是否显示',
    type: 'select',
    optionList: { list: [{ name: '是', value: '1' }, { name: '否', value: '0' }] },
  },
  {
    name: 'elementType',
    label: '元素属性',
    type: 'select',
    optionList: { list: [{ name: '输入框', value: 'text' }, { name: '输入框', value: 'input' }, { name: '密码框', value: 'password' }, { name: '短信验证码', value: 'phoneCode' }] },
  },
  {
    name: 'elementValue',
    label: '元素属性值',
    type: 'input',
  },
  {
    name: 'validate',
    label: '校验正则表达式',
    type: 'input',
  },
  {
    name: 'isDisplayMessage',
    label: '是否显示提示信息',
    type: 'select',
    optionList: { list: [{ name: '是', value: '1' }, { name: '否', value: '0' }] },
  },
  {
    name: 'promptMessage',
    label: '提示信息',
    type: 'editor',
  }
]
const selectAnswerConfig = {
  '1': '是',
  '0': '否'
}
const selectInputConfig = {
  'text': '输入框',
  'input': '输入框',
  'password': '密码框',
  'phoneCode': '短信验证码'
}
function getMergeEditInput(config, data) {
  return config.map((item) => {
    item.initialValue = data[item.name] || data[item.key] || '';
    return item;
  })
}
class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      drawerStatus: {
        visible: false
      },
      editInputConfig: [],
      columns: [
        {
          title: 'Id',
          dataIndex: 'id',
          width: '6%'
        },

        {
          name: 'paraValue',
          title: '参数值',
          type: 'input',
          dataIndex: 'paraValue',
          width: '6%'
        },
        {
          name: 'paraName',
          title: '参数名称',
          dataIndex: 'paraName',
          width: '10%'
        },
        {
          name: 'paraPrompt',
          title: '参数提示',
          dataIndex: 'paraPrompt',
          width: '10%',
        },
        {
          title: '序号',
          dataIndex: 'serialNumber',
          width: '6%'
        },
        {
          name: 'isDisplay',
          title: '是否显示',
          dataIndex: 'isDisplay',
          width: '10%',
          render: (text) => {
            return selectAnswerConfig[text]
          }
        },
        {
          name: 'elementType',
          title: '元素属性',
          dataIndex: 'elementType',
          width: '10%',
          render: (text) => {
            return selectInputConfig[text]
          }
        },
        {
          name: 'elementValue',
          title: '元素属性值',
          dataIndex: 'elementValue',
          width: '14%'
        },
        {
          name: 'validate',
          title: '校验正则表达式',
          dataIndex: 'validate',
          width: '14%'
        },
        {
          name: 'isDisplayMessage',
          title: '是否显示提示信息',
          dataIndex: 'isDisplayMessage',
          width: '10%',
          render: (text) => {
            return selectAnswerConfig[text]
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '20%',
          render: (text, record, index) =>
            this.state.sourcesData.length >= 1 ? (
              <>
                <button type="primary" style={{ margin: '10px' }} onClick={() => this.handleEdit(index)} >编辑</button>
                <Popconfirm title={`确认要删除‘城市${props.name}信息’吗?`} onConfirm={() => this.deleteHandler(index)}>
                  <button type="primary" style={{ margin: '10px' }} >删除</button>
                </Popconfirm>
              </>
            ) : null,
        },
      ],
      sourcesData: [],
    };
    this.$drawerForm = React.createRef();
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.sourcesdata.length !== this.state.sourcesData.length) {
      this.setState({
        sourcesData: nextProps.sourcesdata,
      })
    }
  }
  changeDrawerStatus(visible) {
    this.setState((oldState) => {
      return {
        ...oldState,
        drawerStatus: { visible }
      }
    })
  }
  showEditor(data) {
    this.setState({
      editInputConfig: getMergeEditInput(editConfig, data)
    })
    this.changeDrawerStatus(true)
  }
  handleAdd = () => {
    const { count, sourcesData } = this.state;
    const { cityCode, officialType, accPassType } = this.props;
    const newData = {
      accPassType: accPassType,
      cityCode: cityCode,
      type: officialType,                     // 插入数据的所属类型（0：公积金， 1： 社保）
      id: sourcesData.length + 1,
      serialNumber: sourcesData.length + 1,
      oldSerialNumber: '',
      paraName: 'input',
      paraValue: '',
      paraPrompt: '',
      isDisplay: '0',
      elementType: '',
      elementValue: '0',
      validate: '',
      isDisplayMessage: ''
    };
    this.showEditor(newData)
  };
  deleteHandler = async index => {
    const sourcesData = [...this.state.sourcesData];
    const curData = sourcesData[index];
    const { cityCode, type, serialNumber } = curData
    const responseData = await delTieCardInformation({ cityCode, type, serialNumber });
    if (responseData && responseData.code === '000000') {
      const re = sourcesData.filter((item, i) => {
        return item.id != curData.id
      });
      this.setState({ sourcesData: re });
    } else {
      alert(responseData.message)
    }
  };
  handleEdit = (index) => {
    const newData = [...this.state.sourcesData];
    const item = newData[index];
    const { accPassType } = this.props;
    this.showEditor({ ...item, accPassType });
  }
  // 请求保存编辑的数据
  async saveEditor(validateRes) {
    let postRes = false;
    const dataObj = await saveTieCardInformation(validateRes);
    if (dataObj && dataObj.code === '000000') {
      message.success('操作成功');
      postRes = true;
    } else {
      message.error('操作失败');
    }
    return postRes;
  }
  async onDrawerOk() {
    const { getFieldDecorator, validateFields } = this.$drawerForm.current.props.form;
    let [validateError, validateRes] = await to(validateFields());
    if (validateError) return false;
    const postRes = await this.saveEditor(validateRes);
    if (postRes) {
      this.handleSave(validateRes);
      this.changeDrawerStatus(false);
    }

  };
  handleSave = row => {
    let isAdd = true;
    const { sourcesData } = this.state;
    let newData = [...sourcesData].map((data) => {
      if (data.id === row.id) {
        data = row;
        isAdd = false;
      }
      return data;
    });
    isAdd && (newData = [...sourcesData, row]);
    this.setState({ sourcesData: newData });
  };
  render() {
    const { sourcesData, columns, editInputConfig, drawerStatus } = this.state;
    return (
      <div>
        <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
          添加
        </Button>
        <Table
          className={styles['my-edittable']}
          bordered
          size="small"
          rowKey={(item, index) => index}
          dataSource={sourcesData}
          columns={columns}
        />
        <Modal
          title='注册账号配置修改'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            this.changeDrawerStatus(false);
          }}
          onOk={e => {
            this.onDrawerOk();
          }}
          visible={drawerStatus.visible}
        >
          <FormModal defaultData={editInputConfig} wrappedComponentRef={this.$drawerForm} />
        </Modal>
      </div>
    );
  }
}
export default Login;